package py.com.alfa.escriba.gui.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class ConfigLocator {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private EscribaGUIConfig config = null;
	private String serverPath = null;
	private final String JBOSS_AS5_DIR= "jboss.server.home.dir";
	private final String JBOSS_AS7_DIR= "jboss.server.config.dir";
	private final String TOMCAT_DIR= "catalina.base";
	private final String CONF= "/conf";
	private String filePath="";

	public ConfigLocator(String filePath) {
		  setFilePath(filePath);
		  logger.info("\n======= LOCATING APPLICATION CONFICURATION =======\n");
			serverPath = System.getProperty(JBOSS_AS5_DIR);
			if(null != serverPath){
				logger.info("---JBOSS AS5 CONFIG");
				serverPath = serverPath.concat(CONF);
				loadConfig();
				return;
			}
			serverPath = System.getProperty(JBOSS_AS7_DIR);
			if(null != serverPath){
				logger.info("---JBOSS AS7 CONFIG");
				loadConfig();
				return;
			}
			serverPath = System.getProperty(TOMCAT_DIR);
			if(null != serverPath){
				logger.info("---TOMCAT CONFIG");
				serverPath = serverPath.concat(CONF);
				loadConfig();
				return;
			}
			logger.error("CAN'T LOAD SYSTEM CONFIG - PLEASE VERIFY THE LOCATION OF YOUR CONFIG FILE");
		}

		private void loadConfig(){
			Resource res = new FileSystemResource(serverPath.concat(getFilePath()));
			GenericApplicationContext ctx = new GenericXmlApplicationContext(res);
			config = (EscribaGUIConfig) ctx.getBean("escribaGUIConfig");
		}

		public EscribaGUIConfig getConfig() {
			return config;
		}

		public void setConfig(EscribaGUIConfig config) {
			this.config = config;
		}

		public String getFilePath() {
			return filePath;
		}

		public void setFilePath(String filePath) {
			this.filePath = filePath;
		}
	
}
